package com.learn.netty.http;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpContentCompressor;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.net.InetSocketAddress;

/**
 * HTTP服务端启动类
 * <p>采用 Reactor 模型进行开发的</p>
 * <ul>
 * <li>配置线程池</li>
 * <li>Channel 初始化</li>
 * <li>端口绑定</li>
 * </ul>
 */
public class HttpServer {

    public void start(int port) throws Exception {
        // 主从多线程 Reactor 模型
        // 配置 EventLoopGroup 线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    // 配置 Channel 类型
                    .localAddress(new InetSocketAddress(port))
                    // 设置 ServerSocketChannel 对应的 Handler
                    // handler() 方法是添加到服务端的Pipeline 上
                    // 设置ServerSocketChannel 对应的 Handler
                     .handler(new LoggingHandler(LogLevel.INFO))
                    //  childHandler() 方法是添加到客户端的 Pipeline 上
                    // 设置 SocketChannel 对应的 Handler
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) {
                            // 通过 ChannelPipeline 去注册多个 ChannelHandler
                            ch.pipeline()
                                    .addLast("codec", new HttpServerCodec())                  // HTTP 编解码
                                    .addLast("compressor", new HttpContentCompressor())       // HttpContent 压缩
                                    .addLast("aggregator", new HttpObjectAggregator(65536))   // HTTP 消息聚合
                                    .addLast("handler", new HttpServerHandler());             // 自定义业务逻辑处理器
                        }
                    })
                    // 设置为 true 代表启用了 TCP SO_KEEPALIVE 属性，TCP 会主动探测连接状态，即连接保活
                    // 配置 Channel 参数
                    .childOption(ChannelOption.SO_KEEPALIVE, true);
            // 设置网络监听的端口
            /**
             * bind() 才是真正进行服务器端口绑定和启动的入口
             * sync() 表示阻塞等待服务器启动完成
             */
            ChannelFuture f = b.bind().sync(); // bind() 核心的重点代码
            System.out.println("Http Server started， Listening on " + port);
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        new HttpServer().start(8088);
    }

}
